/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import models.Student;
import models.Students;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author plato
 */
public class AddToXml {

    public AddToXml() {
    }
//    public AddToXml(Document doc) {    
//        this.docOriginal = doc;
//    }
//    

    public boolean checkDublicated(int id, List<Student> listStudent) {

        for (Student student : listStudent) {
            if (student.getId() == id) {
                return true;
            }
        }

        return false;
    }

    public void addStudentToXml(String path, Student student) throws JAXBException {
        try {
            Students students = new Students();
            LoadXml loadXml = new LoadXml(path);
            List<Student> studentList = new ArrayList<>();
            studentList = loadXml.getStudents().getListStudent();
            // check dup
            boolean status = checkDublicated(student.getId(), studentList);
            if (!status) {
                studentList.add(student);
                students.setListStudent(studentList);
                //
                BufferedWriter writer = null;
                writer = new BufferedWriter(new FileWriter(new File(path)));

                JAXBContext jaxbContext = JAXBContext.newInstance(Students.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

                // output pretty printed
                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                jaxbMarshaller.marshal(students, writer);
                writer.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(AddToXml.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public void addObjectToXml(String path, Student objStudent) {
        try {
            String filepath = path;
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);

            // Get the root element
            Node students = doc.getFirstChild();

            Element student = doc.createElement("student");
            students.appendChild(student);
            Element firstNameE = doc.createElement("firstname");
            firstNameE.appendChild(doc.createTextNode(objStudent.getFirstName()));
            Element lastNameE = doc.createElement("lastname");
            lastNameE.appendChild(doc.createTextNode(objStudent.getLastName()));
            Element addressE = doc.createElement("address");
            addressE.appendChild(doc.createTextNode(objStudent.getAddress()));
            Element ageE = doc.createElement("age");
            ageE.appendChild(doc.createTextNode(objStudent.getAge() + ""));
            Element dobE = doc.createElement("dob");
            dobE.appendChild(doc.createTextNode(objStudent.getDob()));
            Element noteE = doc.createElement("note");
            noteE.appendChild(doc.createTextNode(objStudent.getNote()));
            student.appendChild(firstNameE);
            student.appendChild(lastNameE);
            student.appendChild(addressE);
            student.appendChild(ageE);
            student.appendChild(dobE);
            student.appendChild(noteE);

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            Properties properties = new Properties();
            properties.setProperty(OutputKeys.INDENT, "yes");
            properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            properties.setProperty(OutputKeys.METHOD, "xml");
            properties.setProperty(OutputKeys.VERSION, "1.0");
            properties.setProperty(OutputKeys.ENCODING, "UTF-8");
            properties.setProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            transformer.setOutputProperties(properties);
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);

            System.out.println("Done");

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SAXException sae) {
            sae.printStackTrace();
        }

    }
}
